package sms

import (
	"context"
	"fmt"
	"gitee.com/bobo-rs/creative-framework/pkg/sms"
	"gitee.com/bobo-rs/creative-services/consts"
	"gitee.com/bobo-rs/creative-services/framework/logic/config"
)

// Ctx 设置上下文
func (s *sSms) Ctx(ctx context.Context) *sSms {
	s.ctx = ctx
	return s
}

// Service 实例短信服务
func (s *sSms) Service() (sms.Service, error) {
	// 获取SMS渠道配置
	configService := config.New()
	driver, err := configService.GetVar(s.ctx, consts.SysConfigSmsDriver)
	if err != nil {
		return nil, fmt.Errorf(`[%s]短信驱动配置不存在或未设置%s`, consts.SysConfigSmsDriver, err.Error())
	}

	// 实例短信接口
	service, err := sms.New().Driver(driver.String()).Service()
	if err != nil {
		return nil, err
	}

	// 获取SMS渠道配置
	group, err := configService.GetGroupVar(s.ctx, driver.String())
	if err != nil {
		return nil, fmt.Errorf(`请配置[%s]短信服务驱动配置`, consts.SysConfigSmsDriver)
	}

	// 初始化SMS驱动配置
	err = service.Config(group.Map())
	if err != nil {
		return nil, err
	}

	// 返回SMS服务接口
	return service, nil
}
